var { sequelize } = require("../lib/db");
var common = require("../lib/common");
var User = sequelize.import("../models/user");
var crypto = require('crypto');
var moment = require('moment');  

exports.userLogin = function(req, res,next) {
    // sequelize.sync().then(function(){
  //   User.create({
  //     account:"123",
  //     password:"123213213"
  //   });
  // });
  
  //获取url请求客户端ip
  var get_client_ip = function(req) {
    var ip = req.headers['x-forwarded-for'] ||
        req.ip ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress || '';
    if(ip.split(',').length>0){
        ip = ip.split(',')[0]
    }
    return ip;
  };

  if(req.body.username == undefined){
    res.json({"errcode": 40001, "errmsg": "用户名不能为空"});
  }
  if(req.body.pwd == undefined){
    res.json({"errcode": 40001, "errmsg": "密码不能为空"});
  }
  //生成口令的散列值
  var md5 = crypto.createHash('md5');   //crypto模块功能是加密并生成各种散列,此处所示为MD5方式加密
  var end_paw = md5.update(req.body.pwd).digest('hex').toUpperCase();//加密后的密码

  User.getUsers({where:{$or:[{ account: req.body.username},{ mobile:req.body.username }]}}).then(function(users){
    if(users.length == 0){
      return res.json({"errcode": 40003, "errmsg": "用户不存在"});
    }

    if(users[0].loginerrortime != null){
      var loginerrortime = moment(users[0].loginerrortime);
      var logintime = moment(new Date());

      var m =  logintime.diff(loginerrortime, 'm');

      if(m < 60){
        return res.json({errcode: 40004, errmsg: "账户已被锁定60分钟，禁止登陆(请" + (60 - m ) + "分钟后再登陆)" });
      }
    }

    let id = users[0].id;    
    var loginerrorcount = parseInt(users[0].loginerrorcount);
    if((users[0].account === req.body.username || users[0].mobile === req.body.username) && users[0].password === end_paw){

      req.session.user = {
        id: id,
        account: users[0].account,
        lastlogintime:users[0].lastlogintime,
        lastloginip:users[0].lastloginip,
        mobile:users[0].mobile,
        loginerrorcount:users[0].loginerrorcount
      };
      
      User.updateUserById({loginerrortime:null,loginerrorcount:0,lastlogintime:new Date(),lastloginip:get_client_ip(req)},id).then(function(msg){
          return res.json(req.session.user);
      });
      
    }else{
      loginerrorcount++;
      if(loginerrorcount >= 5){
        User.updateUserById({loginerrortime:new Date(),loginerrorcount:5},id).then(function(msg){
          return res.json({"errcode": 40004, "errmsg": "密码错误(已连续错误5次，账户锁定60分钟)"});
        });
      }else if(loginerrorcount < 5){
        User.updateUserById({loginerrorcount:loginerrorcount},id).then(function(msg){
          return res.json({"errcode": 40004, "errmsg": "密码错误"});
        });
      }
    }
  });

};

exports.logout = function (req, res) {
  req.session.destroy();
  res.json({"errcode": 0, "errmsg": "退出完成"});
};

exports.checkLogin = function (req, res, next) {
  //用户已经登录
  if (req.session.user) {
    next();
  }
  else {
    res.json({"errcode": 40001, "errmsg": "您还没有登录"});
  }
};

exports.changepwd = function(req,res,next){
  var oldpwd = req.body.oldPwd;
  if(oldpwd == null){
     res.json({"errcode": 40001, "errmsg": "原密码不能为空"});
  }
  var md5 = crypto.createHash('md5');   //crypto模块功能是加密并生成各种散列,此处所示为MD5方式加密
  var end_paw = md5.update(oldpwd).digest('hex').toUpperCase();//加密后的密码

  User.getUsers({where:{ account: req.body.account } }).then(function(users){
      if(users.length > 0 ){
        var model = users[0];
        if(end_paw != model.password){
          res.json({"errcode": 40002, "errmsg": "原密码不正确"});
        }else if(end_paw === model.password){
          if(req.body.newPwd != req.body.confirmPwd){
            res.json({"errcode": 40002, "errmsg": "两次输入的密码不一致"});
          }else{
            var md5 = crypto.createHash('md5');   //crypto模块功能是加密并生成各种散列,此处所示为MD5方式加密
            User.updateUserById({password:md5.update(req.body.newPwd).digest('hex').toUpperCase()},model.id).then(function(msg){
              return res.json({"errcode": 0, "errmsg": "修改成功"});
            });
          }
        }
      }
  });

}
